//
//  RENetworkManager.swift
//  GoGlobalis
//
//  Created by goglobails on 2018/10/10.
//  Copyright © 2018年 Webkul. All rights reserved.
//

import Foundation
import Alamofire

///网络请求结果
public enum RENetworkResult {
    case success(data: Any, message: String)
    case failed(code: Int, message: String)
}

///网络请求是否成功判断
public enum RENetworkSuccessType {
    case success
    case responseCode
}

////网络请求完成回调
public typealias SKNetworkComplete = (_ result: RENetworkResult)->()

////网络请求完成回调
public typealias SKGetSessionIDComplete = (_ success: Bool, _ message: String)->()

public class RENetworkManager {
    
    private static let manager = RENetworkManager()
    
    ///忽略成功或失败的判断，直接返回成功及返回数据
    private let ignoreApis = ["mobikulhttp/extra/soaplogin",
                              "mobikulmphttp/marketplace/getmysoldordersData",
                              "mobikulmphttp/marketplace/getReviewData",
                              //提交语音导游评价
                              "mobikulmphttp/marketplace/saveRating"]
    
    class func shared() -> RENetworkManager {
        return manager
    }
    
    public class func post(_ url: String, params: [String:Any]?, _ complete: @escaping SKNetworkComplete) {
        let urlString  = BASE_DOMAIN + url
        let headers = self.headers()
        let parameters = self.parameters(params)
        debugPrint("url---：",urlString)
        Alamofire.request(urlString, method: HTTPMethod.post, parameters: parameters, headers: headers).validate().responseJSON { (response) in
            debugPrint("url---：",urlString)
            debugPrint("parameters---：",parameters)
            switch response.result {
            case .success(let resultData):
               debugPrint("response-----：",NSString(data: JSONSerialization.data(withJSONObject: response.result.value ?? "", options: .prettyPrinted) , encoding: String.Encoding.utf8.rawValue) ?? "")
                if let data = resultData as? Dictionary<String, Any> {
                    let message = data["message"] as? String ?? ""
                    if data["success"] != nil {
                        let success: Int = (data["success"] as? Int)!
                        if success == 1 {
                            if data["authKey"] == nil {
                                UserDefaults.standard.set(data["authKey"], forKey: "authKey");
                            }
                            complete(RENetworkResult.success(data: data, message: message))
                        } else if success == 5 {
                           RENetworkManager.requestForGetSessionID(url, params: params, complete)
                        } else {
                            complete(RENetworkResult.failed(code: success, message: message))
                        }
                    } else if data["responseCode"] != nil {
                        let success: Int = (data["responseCode"] as? Int)!
                        if success == 1 || success == 2 {
                            if data["authKey"] != nil {
                                UserDefaults.standard.set(data["authKey"], forKey: "authKey");
                            }
                            complete(RENetworkResult.success(data: data, message: message))
                        } else {
                            complete(RENetworkResult.failed(code: success, message: message))
                        }
                    } else if RENetworkManager.shared().ignoreApis.contains(url) {
                        complete(RENetworkResult.success(data: data, message: message))
                        return
                    } else {
                        let message = data["message"] as? String ?? globalLanguage("Global_NetworkError")
                        complete(RENetworkResult.failed(code: 101, message: message))
                    }
                } else {
                    complete(RENetworkResult.failed(code: 101, message: globalLanguage("Global_NetworkError")))
                }
            case .failure(let error):
                debugPrint("response-----：%@", error)
                complete(RENetworkResult.failed(code: 101, message: globalLanguage("Global_NetworkError")))
            }
        }
    }
    
    ///获取sessionID
    private class func requestForGetSessionID(_ url: String, params: [String:Any]?, _ complete: @escaping SKNetworkComplete) {
        let params = ["password": API_KEY, "username": API_USER_NAME]
        RENetworkManager.post("mobikulhttp/extra/soaplogin", params: params) { (result) in
            switch result {
            case let .success(data, _):
                guard let response = data  as? [String: Any] else {
                    let message = globalLanguage("Global_NetworkError")
                    complete(RENetworkResult.failed(code: 101, message: message))
                    return
                }
                let sessionId = response["sessionId"] as? String ?? ""
                GGLoginManager.shared().saveSessionID(sessionID: sessionId)
                RENetworkManager.post(url, params: params, complete)
            case let .failed(_, message):
                complete(RENetworkResult.failed(code: 101, message: message))
            }
        }
    }
    
    ///上传图片
    public class func upload(_ url: String, params: [String:Any]?, data: [Data], name: [String], _ complete: @escaping SKNetworkComplete) {
        
        let urlString  = BASE_DOMAIN + url
        let parameters = self.parameters(params)
        var headers = self.headers()
        headers["content-type"] = "multipart/form-data"
        Alamofire.upload(multipartFormData: { (formData) in
            
            for (key, value) in parameters {
                let value_string = value as? String ?? ""
                formData.append((value_string as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
            }
            
            for i in 0..<data.count {
                formData.append(data[i], withName: "imageFormKey", fileName: name[i], mimeType: "image/jpeg")
            }
        }, to: urlString, method: .post, headers: headers) { (result) in
            debugPrint("url---：",urlString)
            debugPrint("parameters---：",parameters)
            switch result {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    if let value = response.result.value as? [String: AnyObject]{
                        let json = JSON(value)
                        print(json)
                    }
                }
            case .failure(let error):
                debugPrint("response-----：%@", error)
                complete(RENetworkResult.failed(code: 101, message: globalLanguage("Global_NetworkError")))
            }
        }
    }
    
}

extension RENetworkManager {
    
    //MARK: - 请求头
    public class func headers() -> HTTPHeaders {
        var headers: HTTPHeaders = [:]
        if defaults.object(forKey: "authKey") == nil{
            headers = [
                "apiKey": API_USER_NAME,
                "apiPassword": API_KEY,
                "authKey":""
            ]
        } else {
            headers = [
                "apiKey": API_USER_NAME,
                "apiPassword": API_KEY,
                "authKey":defaults.object(forKey: "authKey") as! String
            ]
        }
        debugPrint("🛡🛡🛡🛡🛡🛡authKey:\(String(describing: headers["authKey"]))")
        return headers
    }
    
    //MARK: - 参数
    public class func parameters(_ params: [String: Any]?) -> [String: Any] {
        
        let websiteId = defaults.object(forKey:"websiteId");
        let deviceToken = defaults.object(forKey:"deviceToken");
        
        //let quoteId = GGLanguageHelper.shared().getLanguageID()
        let storeId = GGLanguageHelper.shared().getLanguageID()
        
        var parameters: [String: Any]!
        if params == nil {
            parameters = [String: Any]()
        } else {
            parameters = params!
        }
        if websiteId == nil {
            parameters["websiteId"] = DEFAULT_WEBSITE_ID
            defaults.set(DEFAULT_WEBSITE_ID, forKey: "websiteId");
            defaults.synchronize();
        } else {
            parameters["websiteId"] = websiteId
        }
        //parameters["quoteId"] = quoteId
        parameters["quoteId"] = "0"
        if deviceToken != nil{
            parameters["token"] = deviceToken
        }
        parameters["storeId"] = storeId
        if GGLoginManager.shared().isLogin() {
            parameters["customerId"] = GGLoginManager.shared().getUserInfo()["customerId"] as! String
        }
        
        //返回的视图的大小和width有关系
        //parameters["width"] = REScreenWidth * 3
        
        if let sessionId = GGLoginManager.shared().getSessionID() {
            parameters["sessionId"] = sessionId
        }
        return parameters
    }
}
